<?php
require_once 'Smarty.class.php';

class MeccanoSmarty extends Smarty
{
   private $request     = NULL;
   private $request_uri = NULL;
   private $category    = NULL;
   private $templates   = array();

   function  __construct($request = array())
   {
      $this->request         = $request;
      $this->request_uri     = (!empty($request) ? implode('/', $request) : 'index') .'.'. config::read('url_extention');

      $this->template_dir    = ROOT . config::read('templates', 'core');
      $this->compile_dir     = ROOT . TPL_COMPILE;
      $this->cache_dir       = ROOT . CACHE;
      $this->left_delimiter  = '{%';
      $this->right_delimiter = '%}';
      $this->debug_tpl       = ROOT . LIBRARY . '/smarty/debug_quicky.tpl';
      $this->templates       = config::read('templates', 'system');
      
      if(empty($this->templates)) $this->templates = array(
         'meta'   => 'default',
         'header' => 'default',
         'footer' => 'default',
         'left'   => 'default',
         'center' => 'default',
         'right'  => 'default'
      );

      # Register System Objects
      @$this->register_object('ErrorHandler', error::getInstance(), array('getErrors', 'getLastError', 'getErrorStatus', 'getSuccess'), FALSE);

      @$this->assign_by_ref('CONFIG', config::getInstance());
      @$this->assign_by_ref('TR', gettext::getInstance());

      # Assign System Variables
      $this->assign('lang', request::getLang('current'));
      $this->assign('default_lang', request::getLang('defaultId'));
      $this->assign('langs', request::getLang('all'));
      $this->assign('authorizedUser', session::user());

      if(config::read('cache_site') && !MODE_DEBUG && !request::adminMode())
         $this->caching = 2;
      else
         $this->caching = 0;

      if(!function_exists('smarty_block_uncacheable'))
      {
         function smarty_block_uncacheable($param, $content, &$smarty)
         {
            return $content;
         }
      }
      $this->register_block('nocache', 'smarty_block_uncacheable', false);
   }


   public function _get_auto_filename($auto_base, $auto_source = null, $auto_id = null)
   {
      if($auto_base == $this->cache_dir)
      {
         return $auto_base .'/'. $this->request_uri;
      }

      return parent::_get_auto_filename($auto_base, $auto_source, $auto_id);
   }

   public function is_cached($tpl_file = null, $cache_id = null, $compile_id = null)
   {
      return parent::is_cached($this->request_uri);
   }

   public function display($resource_name = NULL, $cache_id = NULL, $compile_id = NULL)
   {
      if($resource_name == NULL) $resource_name = $this->request_uri;
      parent::fetch($resource_name, $cache_id, $compile_id, TRUE);
   }

   public function setCategory($category)
   {
      if($this->caching) $this->caching = $category->cache_turn;

      $cache_lifetime = 3600;
      switch($category->cache_life('src'))
      {
         case 1:
            $cache_lifetime = 60 * 15;
            break;
         case 2:
            $cache_lifetime = 60 * 60;
            break;
         case 3:
            $cache_lifetime = 60 * 60 * 4;
            break;
         case 4:
            $cache_lifetime = 60 * 60 * 10;
            break;
         case 5:
            $cache_lifetime = 60 * 60 * 24;
            break;
         case 6:
            $cache_lifetime = 60 * 60 * 24 * 7;
            break;
      }

      $this->cache_lifetime = $cache_lifetime;
      $this->category = $category;
   }


   public function setTemplates($node, $type = 'base')
   {
      $tpl_types = array('base', 'article', 'articles');
      if (!in_array($type, $tpl_types))
         $tpl_type = 'base';

      $templates = array();

      $path = tree_static::getPath($node);
      if(is_array($path) && count($path) > 0)
      {
         $path = array_reverse($path);
         while (($node = array_pop($path)))
         {
            $templates['meta']   = $this->moderateTemplate('meta', $type, $node, $templates);
            $templates['header'] = $this->moderateTemplate('header', $type, $node, $templates);
            $templates['footer'] = $this->moderateTemplate('footer', $type, $node, $templates);
            $templates['left']   = $this->moderateTemplate('left', $type, $node, $templates);
            $templates['center'] = $this->moderateTemplate('center', $type, $node, $templates);
            $templates['right']  = $this->moderateTemplate('right', $type, $node, $templates);
         }
      }
      
      if(empty($templates))
      {
         foreach($this->templates AS $k=>$v)
         {
            $templates[$k] = $this->moderateTemplate($k, $v);
         }
      }

      
      $this->assign('templates', $templates);
      $this->assign('layout_type', $type);
   }
   
   
   /**
    * Moderate template name for different areas of the layout.
    * 
    * @param string $area Layout area
    * @param string $type type of content
    * @param object $node node
    * @return null|string 
    */
   private function moderateTemplate($area, $type, $node = NULL, $templates = array())
   {
      if($type == 'disabled' || (is_object($node) && !empty($node->templates) && $node->templates[$area] == 'disabled')) 
      {
         $this->templates[$area] = 'disabled';
         return NULL;
      }
  
      if(is_object($node) && !empty($node->templates) && !empty($node->templates[$area]))
      {
         if($node->templates[$area] != 'inherit') 
            $this->templates[$area] = $node->templates[$area];
         
         $type = $this->templates[$area] != 'default' ? $this->templates[$area] : $type;
      }

      $template  = NULL;
      $isDefault = TRUE;
      
      switch($area)
      {
         case 'meta':
            $template = 'main.meta.html';
            if(is_object($node) && file_exists($this->template_dir .'/'. $node->id .'.meta.html'))
            {
               $template  = $node->id .'.meta.html';
               $isDefault = FALSE;
            }
            break;
         
         case 'header':
            $template = 'main.header.html';
            if(is_object($node) && file_exists($this->template_dir .'/'. $node->id .'.'. $type .'.header.html'))
            {
               $template  = $node->id .'.'. $type . '.header.html';
               $isDefault = FALSE;
            }
            break;
         
         case 'left':
            $template = 'main.left.html';
            if(is_object($node) && file_exists($this->template_dir .'/'. $node->id .'.'. $type .'.left.html'))
            {
               $template  = $node->id .'.'. $type .'.left.html';
               $isDefault = FALSE;
            }
            break;
         
         case 'center':
            $template = 'main.base.center.html';
            if(is_object($node) && file_exists($this->template_dir .'/'. $node->id .'.'. $type .'.center.html'))
            {
               $template  = $node->id .'.'. $type .'.center.html';
               $isDefault = FALSE;
            } elseif(file_exists($this->template_dir .'/main.'. $type .'.center.html'))
            {
               $template  = 'main.'. $type .'.center.html';
               $isDefault = FALSE;
            }
            break;
         
         case 'right':
            $template = 'main.right.html';
            if(is_object($node) && file_exists($this->template_dir .'/'. $node->id .'.'. $type .'.right.html'))
            {
               $template  = $node->id .'.'. $type .'.right.html';
               $isDefault = FALSE;
            }
            break;
         
         case 'footer':
            $template = 'main.footer.html';
            if(is_object($node) && file_exists($this->template_dir .'/'. $node->id .'.footer.html'))
            {
               $template  = $node->id .'.footer.html';
               $isDefault = FALSE;
            }
            break;
      }
      
      if($isDefault && !empty($templates[$area]) && $templates[$area] != $template)
      {
         $template = $templates[$area];
      }

      return $template;
   }
}